package cn.com.jenson.service.system.service.impl;

import cn.com.jenson.common.AuthEntity;
import cn.com.jenson.entity.user.Role;
import cn.com.jenson.entity.user.User;
import cn.com.jenson.service.system.service.SystemInitService;
import cn.com.jenson.service.user.repository.RoleRepository;
import cn.com.jenson.service.user.repository.UserRepository;
import cn.com.jenson.system.CommonName;
import cn.com.jenson.util.ListUtil;
import cn.com.jenson.util.MD5Util;
import cn.com.jenson.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SystemInitServiceImpl implements SystemInitService {

    @Resource
    private UserRepository userRepository;

    @Resource
    RoleRepository roleRepository;

    /**
     * 初始化多数据，这里默认简单的初始化
     */
    @Override
    public void init() {
        Role role = addAdminRole();
        addAdminAccount(CommonName.ADMIN, CommonName.ADMIN_PASSWORD,role);
        addAdminAccount(CommonName.DEV, CommonName.DEV_PASSWORD,role);
    }

    /**
     * 初始化 具体数据，这里是给 [管理员] 这个用户添加一个 [管理员]
     *
     * @param name     用户名
     * @param password 密码
     */
    private void addAdminAccount(String name, String password,Role role) {
        if (name.isEmpty())
            return;
        User user = userRepository.findByAccount(name);
        if (Objects.nonNull(user))
            return;
        user = new User();
        user.setAccount(name);
        user.setName(name);
        user.setEncipher(StringUtil.randomString(32));
        user.setIsAdmin(true);
        user.setPassword(MD5Util.cryptographicString(password, user.getEncipher()));
        user.setRoleIdList(
                ListUtil.objectToObjectIdList(role)
        );
        userRepository.save(user);
    }

    private Role addAdminRole(){
        Role role = roleRepository.findByIsAdminAndDeleted(true,false);
        if (Objects.isNull(role))
            role = new Role("管理员",true);
        role.setAuthList(
                AuthEntity.toStringList(AuthEntity.authList)
        );
        role = roleRepository.save(role);
        return role;
    }
}
